<template>
  <div>
    <el-card v-if="orderDetail" class="order-card">
      <div slot="header">
        <span>订单基本信息</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="12">
          <p><strong>订单编号：</strong>{{ orderDetail.ordernumber }}</p>
          <p><strong>总金额：</strong>{{ orderDetail.total_amount }}</p>
          <p><strong>状态：</strong>{{ orderDetail.status }}</p>
          <p v-if="orderDetail.status == '退款中'"><strong>退款前：</strong>{{ orderDetail.tk_status }}</p>
          <p><strong>支付方式：</strong>{{ orderDetail.payment_method }}</p>
          <p><strong>创建时间：</strong>{{ formatDateTime(orderDetail.create_time) }}</p>
          <p><strong>更新时间：</strong>{{ formatDateTime(orderDetail.update_time) }}</p>
        </el-col>
        <el-col :span="12">
          <p><strong>收货人：</strong>{{ orderDetail.name }}</p>
          <p><strong>电话：</strong>{{ orderDetail.phone }}</p>
          <p><strong>邮箱：</strong>{{ orderDetail.email }}</p>
          <p><strong>地址：</strong>{{ orderDetail.address_line1 }} {{ orderDetail.address_line2 }}</p>
          <p v-if="orderDetail.membershiptype_name"><strong>会员等级：</strong>{{ orderDetail.membershiptype_name }}</p>
          <p v-if="orderDetail.discount"><strong>折扣优惠：</strong>{{ orderDetail.discount }}%</p>
		  <p v-if="orderDetail.message"><strong>用户留言：</strong>{{ orderDetail.message }}</p>
        </el-col>
      </el-row>
      <div slot="footer">
        <span>订单产品列表</span>
      </div>
      <el-row :gutter="20" v-if="orderDetail.orderProducts && orderDetail.orderProducts.length">
        <el-col :span="6" v-for="product in orderDetail.orderProducts" :key="product.id">
          <el-card class="product-card">
            <img :src="product.img" class="product-image" />
            <div class="product-info">
              <p><strong>产品名称：</strong>{{ product.name }}</p>
              <p><strong>数量：</strong>{{ product.quantity }}</p>
              <p><strong>原价：</strong>{{ product.original_price }}</p>
              <p><strong>折扣价：</strong>{{ product.discount_price || 'null' }}</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <p v-else>暂无产品信息</p>
      <div class="button-group">
        <el-button type="primary" @click="goBack">返回</el-button>
        <el-button type="danger" @click="deleteOrder">删除</el-button>
        <el-button v-if="orderDetail.status === '已完成'" type="warning" @click="updateStatus('已退款')">退款</el-button>
        <el-button v-if="orderDetail.status === '未支付'" type="success" @click="updateStatus('已支付')">已支付</el-button>
        <el-button v-if="orderDetail.status === '未发货'" type="success" @click="updateStatus('已发货')">已发货</el-button>
        <el-button v-if="orderDetail.status === '未发货' || orderDetail.status === '已发货'" type="info" @click="updateStatus('已退款')">退款</el-button>
        <el-button v-if="orderDetail.status === '退款中'" type="info" @click="updateStatus('已退款')">已退款</el-button>
      </div>
    </el-card>
    <div v-else>
      <p>订单详情加载中或订单不存在</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { MessageBox } from 'element-ui';

export default {
  name: 'Orderdetails',
  data() {
    return {
      orderDetail: null, // 用于存储订单详情的数据
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      const token = localStorage.getItem('Authorization');
      if (!token) {
        this.$message.error('未授权访问');
        return;
      }
      const headers = {
        'Content-Type': 'application/json',
        'Authorization': token
      };
      axios.get(`http://localhost:8887/Order/select?id=${this.$route.params.id}`, { headers })
        .then(response => {
          if (response.data.code === 200 && response.data.data) {
            this.orderDetail = response.data.data;
          } else {
            this.$message.error('获取订单详情失败: ' + response.data.message);
            this.orderDetail = null;
          }
        })
        .catch(error => {
          console.error('请求失败:', error);
          this.$message.error('请求失败，请检查网络或联系管理员');
          this.orderDetail = null;
        });
    },
    formatDateTime(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },
    goBack() {
      this.$router.go(-1);
    },
deleteOrder() {
  MessageBox.confirm('确定要删除这个订单吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const token = localStorage.getItem('Authorization');
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': token
    };
    axios.post(`http://localhost:8887/Order/delete`, null, {
      headers,
      params: { id: this.orderDetail.id }
    })
    .then(response => {
      if (response.data.code === 200) {
        this.$message.success(response.data.message);
        this.$router.go(-1);
      } else {
        this.$message.error(response.data.message);
      }
    })
    .catch(error => {
      console.error('请求失败:', error);
      this.$message.error('请求失败，请检查网络或联系管理员');
    });
  }).catch(() => {
    this.$message.info('已取消删除');
  });
},
    updateStatus(newStatus) {
      const order = {
        id: this.orderDetail.id,
        status: newStatus
      };
      const token = localStorage.getItem('Authorization');
      const headers = {
        'Content-Type': 'application/json',
        'Authorization': token
      };
      axios.post('http://localhost:8887/Order/adminupdatestatus', order, { headers })
        .then(response => {
          if (response.data.code === 200) {
            this.$message.success(response.data.message);
            this.fetchData();
          } else {
            this.$message.error(response.data.message);
          }
        })
        .catch(error => {
          console.error('请求失败:', error);
          this.$message.error('请求失败，请检查网络或联系管理员');
        });
    }
  }
};
</script>

<style scoped>
.order-card {
  margin-bottom: 20px;
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-card {
  height: 380px;
}

.product-info {
  padding: 10px;
}

.button-group {
  margin-top: 20px;
}
</style>